<%@ page import="java.io.*,java.util.*, javax.servlet.*, javax.servlet.http.*, 
		org.apache.commons.fileupload.*, org.apache.commons.fileupload.disk.*, 
		org.apache.commons.fileupload.servlet.*, 
		org.apache.commons.io.output.*, java.sql.*, com.twmacinta.util.*"
%>
<%

String course = new String();
String exernum = new String();
String title = new String();

Cookie[] var = request.getCookies();
Cookie courseCookie = null;
Cookie exernumCookie = null;
Cookie titleCookie = null;


for(int i = 0; i< var.length; i++) {
	if(var[i].getName().equals("course")) {
		courseCookie = var[i];
	}
	else if(var[i].getName().equals("exernum")) {
		exernumCookie = var[i];
	}
	
	else if(var[i].getName().equals("title")) {
		titleCookie = var[i];
	}
}

if (course != null) {
	course = courseCookie.getValue();
}

if(exernum != null) {
	exernum = exernumCookie.getValue();
}

if(title != null) {
	title = titleCookie.getValue();
}

System.out.println(course);
System.out.println(exernum);
System.out.println(title);

course = "demo";

String myString = course + title;

MD5 md5 = new MD5();
md5.Update(myString, null);
String hash = md5.asHex();

File file ;
int maxFileSize = 5000 * 1024;
int maxMemSize = 5000 * 1024;
ServletContext context = pageContext.getServletContext();

String base = request.getRealPath("/");
String filePath = base.substring(0, base.lastIndexOf("krusnik") + 8);

if(filePath.contains("/")) {
	filePath += "data/";   
} else {
	filePath += "data\\";   
}
	   
String rep = filePath;

// Verify the content type
String contentType = request.getContentType();

if(contentType.indexOf("multipart/form-data") >= 0) {
	
	DiskFileItemFactory factory = new DiskFileItemFactory();
	// maximum size that will be stored in memory
	factory.setSizeThreshold(maxMemSize);
	// Location to save data that is larger than maxMemSize.
	//xml
	factory.setRepository(new File(rep));
	
	// Create a new file upload handler
	ServletFileUpload upload = new ServletFileUpload(factory);
	// maximum file size to be uploaded.
	upload.setSizeMax(maxFileSize);
	
	// Parse the request to get file items.
	List fileItems = upload.parseRequest(request);
	
	// Process the uploaded file items
	Iterator i = fileItems.iterator();
					  
	while(i.hasNext()) {
		FileItem fi = (FileItem)i.next();
		if(!fi.isFormField()) {
			// Get the uploaded file parameters
			String fieldName = fi.getFieldName();
			String fileName = fi.getName();
			boolean isInMemory = fi.isInMemory();
			long sizeInBytes = fi.getSize();
			
			char[] ext = {fileName.charAt(fileName.length()-4),
					fileName.charAt(fileName.length()-3), 
					fileName.charAt(fileName.length()-2), 
					fileName.charAt(fileName.length()-1)};
			
			String extension = new String(ext);
			
			if (fileName.contains(".docx")) {
				extension = ".docx";	
			}
			            
			if (extension.equals(".pdf") || extension.equals(".odt") || 
				extension.equals(".doc") || extension.equals(".txt") || 
				extension.equals(".docx")) {
				
				Connection connection = null;
				try {
					Class.forName("com.mysql.jdbc.Driver").newInstance();
					String url = "jdbc:mysql://localhost:3306/edcom";
					String username = "root";
					String password = "durendal";
					connection = DriverManager.getConnection(url, username, password);
					  		
					if(connection != null) {
						ResultSet rSet = null;
						String selectData = "SELECT * FROM filetable WHERE course='" + course + "' AND exernum='" + exernum + "'";
						PreparedStatement selectStatement = connection.prepareStatement(selectData);
						rSet = selectStatement.executeQuery();
						String deleteId = "";
						String deleteExtension = "";
						if(rSet.next()) {
							deleteId = rSet.getString(1);
							deleteExtension = rSet.getString(5);
							
							File deleteFile = new File(filePath + deleteId + deleteExtension);
							if(deleteFile.exists()){
								deleteFile.delete();
							}
						}
					  			
						String deleteData = "DELETE FROM filetable WHERE exernum='" + exernum + "' AND course='" + "demo" + "'";
						
						PreparedStatement deleteStatement = connection.prepareStatement(deleteData);
						deleteStatement.execute();
						deleteStatement.close();			
						
						String queryString = "INSERT INTO filetable(id, course, exernum, title, extension) VALUES ('"+ hash +"', '"+ course +"', '"+ exernum +"', '"+ title +"', '"+ extension +"')";
						  
						PreparedStatement pstatement = connection.prepareStatement(queryString);
						pstatement.execute(queryString);
						pstatement.close();
								            	    
						connection.close();
					}
					else System.out.println("CANNOT ESTABLISH CONNECTION");
				} catch(Exception e) { 
					e.printStackTrace(); 
				}
					
				// Write the file
				if(fileName.lastIndexOf("\\") >= 0) {
					file = new File( filePath + hash.substring( fileName.lastIndexOf("\\")) + extension) ;
				} else {
					file = new File( filePath + hash.substring(fileName.lastIndexOf("\\")+1) + extension) ;
				}
				fi.write(file);
			} else {
				out.println("Cannot upload here. Unsupported file format.");
			}
		}
	}
} else {
	out.println("No file uploaded."); 
}

%>